package com.fengmi.controller;

import com.fengmi.entity.SysUser;
import com.fengmi.service.UserService;
import com.fengmi.utils.security.JwtUtils;
import com.fengmi.utils.security.RsaUtils;
import com.fengmi.vo.InfoResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.security.PublicKey;

/**
 * Author: 施俊豪
 * Date: 2022/2/5 23:58
 * Note: 用户控制器
 */
@Api(description = "用户控制器")
@RestController
@RequestMapping("user")
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation("登录方法")
    @PostMapping("/login")
    public InfoResult login(@ApiParam("登录用户名和密码") @RequestBody SysUser user){
        return userService.login(user);
    }

    @RequestMapping("/verify")
    public InfoResult verify(@RequestHeader("token") String token){
        // 检查token是否为空
        if(StringUtils.isEmpty("token")){
            return new InfoResult(false,"令牌不能为空","");
        }

        try {
            // 获取公钥
            PublicKey publicKey = RsaUtils.getPublicKey(ResourceUtils.getFile("classpath:rsa.pub").getPath());

            // 生成token,检查这句话是否出现异常，如果出现异常,则token无效，否则，token可用
            Object infoFromToken = JwtUtils.getInfoFromToken(token, publicKey, SysUser.class);
            return new InfoResult(true,"令牌有效","");
        } catch (Exception e) {
            //e.printStackTrace();
            return new InfoResult(false,"令牌无效!!!","");
        }

    }
}
